import { dataBsePath } from "./../main";
import { app, ipcMain, IpcMainEvent, IpcMainInvokeEvent } from "electron";
import { ICreateWs } from "../types/ws.ts";
import { closeWindow, createWindow, getTargetWindow } from "../window/CreateWindow.ts";
import { closeWs, createWs } from "../ws";
import { IcreateWindowParams } from "../types/window.ts";
import { MergeMessage } from "../utils/merge.ts";

export function UserEvent() {
  // 连接ws 合并数据
  ipcMain.handle("connectWs", async (_event: IpcMainInvokeEvent, params: ICreateWs) => {
    try {
      const defaultDownloadPath = app.getPath("downloads");
      MergeMessage(params.id, params.messages, params);
      createWs(params);
      return {
        defaultDownloadPath,
        dataBsePath,
      };
    } catch (error) {
      console.log("登录出现错误", error);
      return null;
    }
  });

  // 打开主页面 关闭login
  ipcMain.on("login", (_event: IpcMainEvent) => {
    closeWindow("login");
    createWindow("message", 1000, 710, "home");
  });

  // 打开注册 关闭登录
  ipcMain.on("register", (_event: IpcMainEvent, params: IcreateWindowParams) => {
    closeWindow("login");
    createWindow(params.path, params.width, params.height, "register");
  });

  // 推出登录
  ipcMain.on("logout", (_event: IpcMainEvent) => {
    closeWs();
    closeWindow("home");
    createWindow();
  });

  // 关闭页面
  ipcMain.on("closePage", (_event: IpcMainEvent, name: string, isBackLogin: boolean = false) => {
    let target = getTargetWindow(name);
    if (target) target.close();
    if (isBackLogin) createWindow();
  });

  // 监听关闭ws
  ipcMain.on("closeWs", () => {
    closeWs();
  });
}
